﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Collada141;
using System.Diagnostics;
using Microsoft.Xna.Framework;

namespace DAREContentProcessor
{
    [ContentImporter(".dae", DisplayName = "Collada - Importer", DefaultProcessor = "CModelFullExporter")]
    public class CColladaImporter : ContentImporter<NodeContent>
    {
        #region Fields

        COLLADA m_colladaDoc;
        NodeContent m_root;
        #endregion

        #region CTOR
        #endregion

        public override NodeContent Import(string filename, ContentImporterContext context)
        {
            m_colladaDoc = COLLADA.Load(filename);

            NodeContent root = GenerateHierarchy(m_colladaDoc.Items.OfType<library_visual_scenes>().SingleOrDefault());

            return root;
        }

        #region Method

        private void GenerateGeometry(library_geometries geo)
        {

        }

        private NodeContent GenerateHierarchy(library_visual_scenes vs)
        {
            Debug.Assert(vs.visual_scene.Length == 1);
            NodeContent root = null;
            if (vs.visual_scene[0].node.Length > 1)
            {
                root = new NodeContent()
                {
                    Name = "RootNode",
                    Transform = Matrix.Identity
                };
                HierachyNode(root, vs.visual_scene[0].node[0]);
            }
            else
                root = HierachyNode(null, vs.visual_scene[0].node[0]);
            return root;
        }

        private NodeContent HierachyNode(NodeContent content, node node)
        {
            NodeContent _node = null;
            if (node.type == NodeType.JOINT)
                _node = new BoneContent();
            else
                _node = new NodeContent();
            if (content != null)
                content.Children.Add(_node);
            _node.Name = node.name;
            _node.OpaqueData.Add("NODE", node);
            foreach (var child in node.node1)
                HierachyNode(_node, child);
        }
        #endregion
    }
}
